import SparkMD5 from 'spark-md5'
import { fileUpload, fileMerge, checkUploadFile } from '../../api/movie'
import { ref } from 'vue'
export function useUpload () {
  let files = []
  let hashName = ''
  let fileType = ''
  const progress = ref(0)
  // 影片选择
  const onSelectChange = (fileList) => {
    const spark = new SparkMD5()
    files = []
    progress.value = 0
    const file = fileList[0]
    const size = 1024 * 1024 * 5 // 5M
    let start = 0
    fileType = file.name.split('.')[1]
    // 文件切片
    while (start < file.size) {
      const fileBlob = file.slice(start, start + size)
      spark.append(fileBlob)
      files.push(fileBlob)
      start += size
    }
    hashName = spark.end() // 拿到文件的md5值
    // newFile.type = file.type
    console.log(files, file, hashName)
  }
  const stop = false
  // 开始上传文件
  async function upload () {
    let resualt // 返回上传结果
    await checkUploadFile({ fileName: hashName }).then(async res => {
      if (res.status === 1) {
        resualt = res
        progress.value = 100
      } else {
        let fileIndexs = []
        if (res.status === 2) {
          fileIndexs = res.files.map(item => parseInt(item.split('-')[1]))
        }
        await uploadStart(fileIndexs)
        // 上传完成，进行合并
        await fileMerge({ fileName: hashName, fileType }).then(res => {
          // console.log(res)
          resualt = res
        })
      }
    })
    async function uploadStart (fileIndexs = []) {
      for (let i = 0; i < files.length; i++) {
        if (fileIndexs.length && fileIndexs.includes(i)) {
          continue
        }
        if (stop) {
          break
        }
        const formData = new FormData()
        formData.append('file', files[i])
        formData.append('fileName', `${hashName}-${i}`)
        formData.append('fileType', fileType)
        await fileUpload(formData).then(res => {
          // console.log(res)
          progress.value = Math.ceil((i + 1) / files.length * 100)
        })
      }
    }
    return resualt
  }
  const avtarInfo = ref({ fileName: '', fileType: '', noSlice: 1 })
  function onAvtarChange (fileList) {
    const file = fileList[0]
    console.log(file)
    avtarInfo.value.fileType = file.type.split('/')[1]
    const spark = new SparkMD5()
    spark.append(file.slice(0, file.size))
    avtarInfo.value.fileName = spark.end()
    console.log(avtarInfo.value.fileName)
  }
  return {
    onSelectChange,
    upload,
    progress,
    onAvtarChange,
    avtarInfo
  }
}
